package cn.stronglink.esm27.collection.iot.devices.esm27.response.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;

import cn.stronglink.esm27.collection.core.message.IMessageHandle;
import cn.stronglink.esm27.collection.core.util.ContextUtils;
import cn.stronglink.esm27.collection.iot.devices.esm27.message.MQMessageOfESM27;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.DeviceEntity;
import cn.stronglink.esm27.collection.iot.devices.esm27.response.entity.ESM27ResponseMessageEntity;
import cn.stronglink.esm27.collection.mq.TopicSender;
import io.netty.channel.ChannelHandlerContext;

/**
 * 同步时间的反馈
 * @author yuzhantao
 *
 */
public class SetDateTimeReturnHandle implements IMessageHandle<ESM27ResponseMessageEntity, Object> {
	private final static String ACTION_CODE="SetDateTimeReturn";
	private final static String TOPIC_NAME="ESM27ToService";		// MQ发送主题
	private final static Logger logger = LogManager.getLogger(SetDateTimeReturnHandle.class.getName());
	private TopicSender topicSender = (TopicSender) ContextUtils.getBean("topicSender");
	
	@Override
	public boolean isHandle(ESM27ResponseMessageEntity t) {
		if(t.getCommandCode()==0x06) {
			return true;
		}else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, ESM27ResponseMessageEntity t) {
		DeviceEntity device = new DeviceEntity();
		device.setDeviceAddress(t.getDeviceAddress());
		
		MQMessageOfESM27 message = new MQMessageOfESM27();
		message.setActioncode(ACTION_CODE);
		message.setTimeStamp(System.currentTimeMillis());
		message.setAwsPostdata(device);

		switch(t.getCommandRunStatus()) {
		case 0:
			message.setIsSuccess(true);
			break;
		case 5:
			message.setIsSuccess(false);
			message.setErrorMessage("保存失败");
			break;
		default:
			message.setIsSuccess(false);
			message.setErrorMessage("未知信息");
			break;
		}
		
		String json = JSON.toJSONString(message);
		topicSender.send(TOPIC_NAME, json);
		logger.info("发送[{}]到MQ完成:{}","同步时间的反馈信息",json);
		
		return null;
	}

}
